<?php

namespace app\backstage\controller;

use app\backstage\model\Link;
use think\Controller;
use think\Db;
use think\facade\Request;

class Vivo extends Controller
{

    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => ['activeReport']],
    ];

    public function index()
    {
        return $this->fetch();
    }

    public function list_data()
    {
        $params = Request::param('', '', 'strip_tags');
        $Vivo = \think\facade\App::model('Vivo', 'logic');
        $result = $Vivo->getList($params);

        return sucJson($result['list'], $result['count']);
    }

    public function add()
    {
        if( Request::isGet() ){
            return $this->fetch();
        }

        $params = Request::post('','','strip_tags,trim');

        $verify_result = $this->validate($params, 'Vivo.add');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $Vivo = \think\facade\App::model('Vivo','logic');
        while (true) {
            $mySign = $this->randStr();
            $info = $Vivo->getInfo(['mysign' => $mySign]);
            if (!$info) {
                break;
            }
        }
        $params['mysign'] = $mySign;
        $params['channel_id'] = request()->_user->id;
        $ManagerUser = \think\facade\App::model('Account');
        $m = $ManagerUser->getOne(['id' => $params['channel_id']], 'parent_id');
        $params['agent_id'] = $m['parent_id'];


        $r = $Vivo->addInfo($params);
        if ($r) {
            return ['code'=>100,'msg'=>'操作成功'];
        }
        return ['code'=>102,'msg'=>'操作失败'];
    }

    private function randStr($length = 8) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    public function delete()
    {
        $params = Request::get('','','strip_tags,trim');

        $verify_result = $this->validate($params, 'Vivo.info');
        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }
        $Vivo = \think\facade\App::model('Vivo','logic');
        return $Vivo->editInfo(['id' => $params['id']], ['status' => 0]);
    }

    /**
     * 测试上报
     * @return bool|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function activeReport()
    {
        $user = request()->_user;
        $channelid = $user->id;
        $mysign = input('mysign', '');
        $where[] = ['mysign', '=', $mysign];
        $where[] = ['channel_id', '=', $channelid];
        $adinfo = Db::table('quick_ad_account_vivo')->where($where)->find();
        if (!$adinfo) {
            die('未查询到数据源ID：' . $mysign . ' 的vivo账户信息，无法检测上报');
        }
        $qas = getMyQas($user,1);
        if (!$qas){
            die('账号未授权App');
        }
        $packageName = Db::table("quick_app")->where("id", $qas[0])->value('package_name');
        $srcId = $adinfo['akey'];//ds-202303130243
        $access_token = $adinfo['token'];

        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

        $url = 'https://marketing-api.vivo.com.cn/openapi/v1/account/advertiser/query?access_token=' . $access_token . '&timestamp=' . $msectime . '&nonce=' . md5($msectime);
        $res_str = httpGet($url);
        $res = json_decode($res_str, true);
        $accList = null;
        if (isset($res['code']) && $res['code'] === 0 && isset($res['data']['list']) ){
            $accList = array_column($res['data']['list'],null,'name');
        }

        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $url = 'https://marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload?access_token=' . $access_token . '&timestamp=' . $msectime . '&nonce=' . md5($msectime);
        if ($accList && isset($accList[$adinfo['accountname']])){
            $advertiser_id = $accList[$adinfo['accountname']]['uuid'];
            $url .= "&advertiser_id=".$advertiser_id;
            Db::table('quick_ad_account_vivo')->where('id', $adinfo['id'])->setField("advertiser_id", $advertiser_id);
        }
        $data = [
            'srcType' => 'Quickapp',
            'pkgName' => trim($packageName),
            'pageUrl' => 'read',
            'srcId' => $srcId,
            'dataList' => [
                'cvType' => 'PAY',
                'cvTime' => $msectime,
                'requestId' => '',
                'creativeId' => ''
            ],
        ];
        $res_str = httpPost($url, json_encode($data));
        return $res_str;
    }

}


